<?php

namespace app\index\controller;

use app\common\controller\Apicommon;
use app\index\model\Device;
use app\index\model\Door;
use app\index\model\GearRecord;
use app\index\model\SecurityCheckRecord;
use app\index\model\UnusualRecord;

/**
 * 安检设备管理
 * @package app\index\controller
 */
class Securitycheck extends Apicommon
{
    public function initialize()
    {
        //parent::initialize();
        header('Access-Control-Allow-Headers: content-type,authorization,token');
        header('Access-Control-Allow-Methods: PUT, GET, POST, DELETE, OPTIONS');
        header('Access-Control-Allow-Origin: *');
        if($_SERVER['REQUEST_METHOD'] == 'OPTIONS'){
            echo 1;die;
        }
        // 默认跳转模块
        if(empty(session('user_auth.uid'))){
            $this->redirect('login');
        }else{
            $this->uid = session('user_auth.uid');
        }
    }

    /**
     * 预警设备列表
     * @param int $page 页码
     * @param int $limit 一页显示数量
     * @return mixed
     */
    public function warningDevice()
    {
        $query = $this->request->request();

        // 处理查询
        $where = [];
        // 按设备编号查询
        if (!empty($query['device_serial'])) $where[] = ['device.device_serial', '=', $query['device_serial']];

        $device = new Device();

        $record = $device->where($where)->alias('device')->field('device.*,door.door_serial')
            ->leftJoin('door', 'door.id = device.door_id')
            ->where([
                ['warning_time','<=',date('Y-m-d')],
                ['device.status', 'neq', 6], // 排除已报废的设备
                ['device.status', 'neq', 4]  // 排除安检中的设备
            ])
            ->paginate(input('limit', 10), false);
        $list = $record->items();

        $this->assign('pages', $record->render());
        $this->assign('row', $list);
        return $this->fetch();
    }

    /**
     * 开始安检
     * @param int $ids 设备ID
     */
    public function securityCheck($ids = null)
    {
        $ids = $ids ?: $this->request->request('ids');
        if (empty($ids)) $this->error_json('没有选择设备');

        // 查找已过预警时间，状态不是'已报废（6）'、'安检中（4）'的设备
        $device = new Device();
        $where = [
            ['id', 'in', $ids],
            ['status', 'neq', 6], // 排除已报废的设备
            ['status', 'neq', 4], // 排除安检中的设备
        ];
        $list = $device->where($where)->select()->toArray();

        if (empty(count($list))) $this->error_json('选择的设备中没有可安检的设备');

        $device_ids = array_column($list,'id');
        $str_device_ids = implode(',', $device_ids);

        // 更新设备状态
        $sql = "update " . $device->getTable() . " set `last_status` = `status`,`status` = 4 where id in ($str_device_ids) ";
        $device->execute($sql);

        // 创建安检记录
        $check_record = new SecurityCheckRecord();
        foreach ($device_ids as $device_id) {
            $data = [
                'device_id' => $device_id,
                'operate_id' => $this->uid,
                'status'=>1
            ];
            $check_record->create($data);
        }
        $this->success_json('成功添加 '.count($device_ids).' 台设备到安检中');
    }

    /**
     * 设备安检记录
     * @param int $page 页码
     * @param int $limit 一页显示数量
     * @return mixed
     */
    public function checkRecord()
    {
        $query = $this->request->request();

        // 处理查询
        $where = [];
        // 按设备编号查询
        if (!empty($query['device_serial'])) $where[] = ['device.device_serial', '=', $query['device_serial']];

        $record_model = new SecurityCheckRecord();

        $field = "
            record.id,
            record.status,
            record.createtime check_time,
            device.device_serial,
            device.device_name,
            device.device_model,
            admin.nickname operator_name
        ";
        $record = $record_model->where($where)->alias('record')->field($field)
            ->leftJoin('device', 'device.id = record.device_id')
            ->leftJoin('admin_user admin', 'admin.id = record.operator_id')
            ->order('record.updatetime','desc')
            ->where('record.status','neq',3)
            ->paginate(input('limit', 10), false);
        $list = $record->items();

        $this->assign('pages', $record->render());
        $this->assign('row', $list);
        return $this->fetch();
    }

    /**
     * 结束安检
     * @param int $id
     */
    public function finishCheck($id = null)
    {
        $record = SecurityCheckRecord::get(['id'=>$id,'status'=>1]);
        if (!$record) return '未找到可操作的记录';

        if ($this->request->isPost()){
            $params = $this->request->request();
            if (empty($check_time = $params['check_time'])) $this->error_json('下次报警时间不能为空');
            if (empty($warning_time = $params['warning_time'])) $this->error_json('下次检修时间不能为空');
            if (empty($scrap_time = $params['scrap_time'])) $this->error_json('报废时间不能为空');

            if (strtotime($check_time) < time() ) $this->error_json('下次报警时间不能早于当期日期');
            if (strtotime($warning_time) < time() ) $this->error_json('下次检修时间不能早于当期日期');
            if (strtotime($scrap_time) < time() ) $this->error_json('报废时间不能早于当期日期');

            $device_id = $record->device_id;
            $record->status = 2;
            $record->operator_id = $this->uid;
            $record->save();

            // 更新设备状态及下次安检信息
            Device::update([
                'check_time'=>$check_time,
                'warning_time'=>$warning_time,
                'scrap_time'=>$scrap_time,
                'status'=>3
            ],['id'=>$device_id]);
            $this->success_json('操作成功');
        }
        $this->assign('device_id',$id);
        return $this->fetch();
    }

    /**
     * 取消安检
     * @param int $id
     */
    public function cancelCheck($ids = null)
    {
        $ids = $ids ?: $this->request->request('ids');
        if (empty($ids)) $this->error_json('没有选择设备');

        $record = new SecurityCheckRecord();
        $where = [
            ['id', 'in', $ids],
            ['status', '=', 1]
        ];
        $list = $record->where($where)->select()->toArray();
        if (empty(count($list))) $this->error_json('选择的设备中没有可操作的设备');

        $device_ids = array_column($list,'id');
        $str_device_ids = implode(',', $device_ids);

        // 更新记录状态
        $record->update(['status' => 3], [
            ['id', 'in', $ids],
            ['status', '=', 1]
        ]);

        // 更新设备状态
        $device = new Device();
        $sql = "update " . $device->getTable() . " set `status` = `last_status` where id in ($str_device_ids) ";
        $device->execute($sql);

        $this->success_json('成功取消 '.count($device_ids).' 台设备的安检');
    }

    /**
     * 安全柜门
     * @param int $page 页码
     * @param int $limit 一页显示数量
     * @return mixed
     */
    public function door()
    {
        $door_list = Door::alias('door')
            ->field('door.id,door.door_serial,gear.gear_serial')
            ->leftJoin('gear','gear.id = door.gear_id')
            ->where('door.is_security',1)
            ->select();


        $door_data = [];
        foreach ($door_list as &$door_item) {
            $temp = [
                'door_id'=>$door_item->id,
                'door_serial'=>$door_item->door_serial,
                'gear_serial'=>$door_item->gear_serial,
                'dev_num'=>0,
                'dev_list'=>'',
                'check_time'=>0,
            ];
            $door_data[$door_item->id] = $temp;
        }

        $door_id = array_column($door_list->toArray(),'id');
        
        // 查询设备
        $device_list = Device::order('check_time','asc')->whereIn('door_id',$door_id)->where('door_id','neq',0)->select();

        foreach ($device_list as $item) {
            if (empty($door_data[$item->door_id]['check_time'])) {
                $door_data[$item->door_id]['check_time'] = $item->check_time;
            }
            $door_data[$item->door_id]['dev_num'] = empty($door_data[$item->door_id]['dev_num']) ? 1 : $door_data[$item->door_id]['dev_num'] + 1;
            $door_data[$item->door_id]['dev_list'] = (!empty($door_data[$item->door_id]['dev_list']) ? $door_data[$item->door_id]['dev_list'] . ',' : '') . $item->device_serial;
        }
        $this->assign('pages', 1);
        $this->assign('row', $door_data);
        return $this->fetch();
    }

    // 添加安全门
    public function add_overhaul_door()
    {
        if ($this->request->isPost()) {
            $door_id = $this->request->request('door_id');
            if (empty($door_id)) $this->error_json('未选择柜门');

            $door_list = Door::get(['is_security'=>0,'id'=>$door_id]);
            if (empty($door_list)) $this->error_json('该柜门已经是安检柜,不能重复设置');

            $check_dev = Device::get(['door_id'=>$door_id]);
            if ($check_dev) $this->error_json('该柜子里有设备，不能设为安检柜');

            $door_list->is_security = 1;
            $door_list->save();
            $this->success_json('操作成功');
        }

        // 查找柜子为空且不是安全门的柜门列表
        $door_list = Door::all(['is_security'=>0,'status'=>0]);
        $door_list = $door_list ? $door_list->toArray() : [];
        $this->assign('door_list',$door_list);
        return $this->fetch();
    }

    public function cancel_overhaul_door($ids = null)
    {
        $ids = $ids ?: $this->request->request('ids');
        if (empty($ids)) $this->error_json('未选择柜门');


        // 查找在这些柜子里的设备
        $device = new Device();
        $check_device = $device->where('door_id','in',$ids)->select()->toArray();
        if (!empty($check_device)) {
            $this->error_json('所选的柜子中还有设备，不能取消安全柜');
        }

        $door = new Door();
        $door->where([
            ['id','in',$ids],
            ['is_security','=',1]
        ])->update(['is_security'=>0]);

        $this->success_json('操作成功');

    }
}
